import 'dart:convert';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import '../core/app_initializer.dart';

class AppCacheManager {
  AppCacheManager._();

  static CacheManager get instance => AppInitializer.cacheManager;

  /// 存储数据，支持泛型
  static Future<void> set<T>(
    String key,
    T value, {
    required Duration ttl,
  }) async {
    final expireAt = DateTime.now().add(ttl).millisecondsSinceEpoch;

    final wrapper = {
      'expireAt': expireAt,
      'type': T.toString(),
      'data': value,
    };

    final jsonString = jsonEncode(wrapper);
    await instance.putFile(
      key,
      utf8.encode(jsonString),
      fileExtension: 'json',
    );
  }

  /// 读取数据，支持泛型
  static Future<T?> get<T>(String key) async {
    try {
      final fileInfo = await instance.getFileFromCache(key);
      if (fileInfo == null) return null;

      final content = await fileInfo.file.readAsString();
      final wrapper = jsonDecode(content) as Map<String, dynamic>;

      final expireAt = wrapper['expireAt'] as int;
      if (DateTime.now().millisecondsSinceEpoch > expireAt) {
        await instance.removeFile(key);
        return null;
      }

      final data = wrapper['data'];

      // 基本类型
      if (T == String) return data as T;
      if (T == int) return (data as num).toInt() as T;
      if (T == double) return (data as num).toDouble() as T;
      if (T == bool) return data as T;

      // Map
      if (T == Map<String, dynamic>) {
        return Map<String, dynamic>.from(data) as T;
      }

      // List<String>
      if (T == List<String>) {
        return List<String>.from(data) as T;
      }

      // List<int>
      if (T == List<int>) {
        return List<int>.from(data) as T;
      }

      // List<Map<String,dynamic>>
      if (T == List<Map<String, dynamic>>) {
        return (data as List).map((e) => Map<String, dynamic>.from(e)).toList()
            as T;
      }

      // 其他类型直接返回
      return data as T;
    } catch (_) {
      return null;
    }
  }

  /// 删除缓存
  static Future<void> remove(String key) async {
    await instance.removeFile(key);
  }
}
